﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;

using Twipler.App.Machine.Instructions;

namespace Twipler.App.Parse.Code
{
    public class Instructions
    {        
        public static List<string> List { get; private set; }
        public static List<Type> _types;
        private static List<string> _list;
        
        static Instructions()
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            Type iInstruction = typeof(App.Machine.Instruction);

            _types = new List<Type>();
            _list = new List<string>();

            foreach (Type t in asm.GetTypes())
            {
                if (iInstruction.IsAssignableFrom(t) && (t.Name.ToLower() != "instruction"))
                {
                    _types.Add(t);
                    _list.Add(t.Name.ToLower());
                }
            }            
        }

        public static bool Exists(string name)
        {
            name = name.ToLower();
            return _list.Exists(p => p == name);
        }

        public static string FollowedByJunk(string name)
        {
            name = name.ToLower();
            
            string bestMatch = _list
                             .FindAll(str => name.StartsWith(str))
                             .OrderBy(str => str.Length)
                             .FirstOrDefault();

            if (string.IsNullOrEmpty(bestMatch))
                return name;
            
            return name.Substring(bestMatch.Length);
        }

        public static Type GetType(string name)
        {
            name = name.ToLower();
            return _types.Find(t => t.Name.ToLower() == name);
        }
    }
 

}